package com.atguigu.tingshu.order.receiver;

import com.atguigu.tingshu.common.constant.KafkaConstant;
import com.atguigu.tingshu.order.service.OrderInfoService;
import jakarta.annotation.PostConstruct;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.redisson.api.RBlockingDeque;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * @author atguigu-mqx
 * @ClassName OrderReceiver
 * @description: TODO
 * @date 2024年04月24日
 * @version: 1.0
 */
@Component
public class OrderReceiver {

    //  获取客户端对象
    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private OrderInfoService orderInfoService;

    //  使用spring task 定时任务; cron ; xxl-job: 分布式定时任务调度框架.
    //  添加注解：表示自动调用方法执行.
    @PostConstruct
    public void orderCancel(){
        //  创建一个线程.
        new Thread(()->{
            //  死循环.
            while (true){
                //  获取到队列
                RBlockingDeque<Object> blockingDeque = this.redissonClient.getBlockingDeque(KafkaConstant.QUEUE_ORDER_CANCEL);
                //  获取队列中的数据
                String orderIdStr = null;
                try {
                    orderIdStr = (String) blockingDeque.take();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                if (!StringUtils.isEmpty(orderIdStr)){
                    //  调用取消订单方法.
                    this.orderInfoService.orderCancel(Long.parseLong(orderIdStr));
                }
            }
        }).start();
    }

    /**
     * 监听订单支付成功消息
     * @param record
     */
    @KafkaListener(topics = KafkaConstant.QUEUE_ORDER_PAY_SUCCESS)
    public void orderPaySuccess(ConsumerRecord<String,String> record){
        //  获取数据
        String orderNo = record.value();
        //  判断
        if (!StringUtils.isEmpty(orderNo)){
            //  修改订单状态.
            orderInfoService.orderPaySuccess(orderNo);
        }
    }
}
